#include "qdataset.h"

QDataSet::QDataSet(){
    this->sql = "";
    this->args.clear();
    this->error = QSqlError("","",QSqlError::NoError);
}

QDataSet::QDataSet(QString sql,QVariantList args,QSqlError error){
    this->sql = sql;
    this->args = args;
    this->error = error;
}

QDataSet::QDataSet(QSqlQuery query){
    this->read(query);
}

bool QDataSet::isEmpty(){
    if(this->tables.count() == 0){
        return true;
    }
    return false;
}

bool QDataSet::hasError(){
    return this->error.type() != QSqlError::NoError;
}

QString QDataSet::message(){
    if(this->hasError()){
        return this->error.text();
    }
    return QString("");
}

void QDataSet::print(bool count,bool lastAffect){
    qDebug() << "sql:" << this->sql;
    qDebug() << "args:"<< this->args;
    qDebug() << "error:" << this->hasError();
    qDebug() << "message:" << this->message();
    if(count){
        qDebug() << "table:" << this->count();
    }
    if(lastAffect){
        qDebug() << "lastId:" << this->lastId;
        qDebug() << "affected:" << this->affected;
    }
    qDebug();
}

QDataTable QDataSet::first(){
    if(this->tables.count() == 0){
        return QDataTable();
    }
    return this->tables.at(0);
}

QDataTable QDataSet::at(int idx){
    if(idx < 0){
        return QDataTable();
    }
    if(idx > this->tables.count()){
        return QDataTable();
    }
    if(this->tables.count() == 0){
        return QDataTable();
    }
    return this->tables.at(idx);
}

QDataTable QDataSet::last(){
    if(this->tables.count() == 0){
        return QDataTable();
    }
    return this->tables.last();
}

QVariant QDataSet::scalar(){
    return this->first().scalar();
}

int QDataSet::count(){
    return this->tables.count();
}

void QDataSet::read(QSqlQuery query){
    this->sql = query.lastQuery();
    this->args.clear();
    for(int i=0;i<query.boundValues().count();i++){
        this->args << query.boundValue(i);
    }
    this->lastId = query.lastInsertId();
    this->affected = query.numRowsAffected();
    this->error = query.lastError();
    do{
        auto record = query.record();
        if(record.count() == 0){continue;}

        // get columns
        QDataTable table;
        QVector<QSqlField> columns;
        for(int i=0;i<record.count();i++){
            auto field = record.field(i);
            columns.append(field);
            table.columns.append(field.name());
        }

        // get rows
        while (query.next()){
            QVariantMap row;
            for(int i=0;i<columns.count();i++){
                auto item = columns.at(i);
                auto name = item.name();
                auto value = query.value(name);
                row[name] = value;
            }
            table.rows.append(row);
        }
        this->tables.append(table);
    }while (query.nextResult());
}
